package com.yhz.springboot.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Author yhz
 * @Data 11:16 2020/2/23
 * @Description 文件上传下载
 */
public class FileUtil {
    //文件上传
    public static String upload(MultipartFile file, String path) throws IOException {
        //返回的本地文件地址
        String LocaPath ="";
        if(!file.isEmpty()){
            //上传文件名
            String fileName = file.getOriginalFilename();
            File filePath = new File(path,fileName);
            //判断路径是否存在
            if(!filePath.getParentFile().exists()){
                filePath.getParentFile().mkdir();
            }
            //将上传的文件进行保存
            file.transferTo(new File(path+File.separator+fileName));
            LocaPath=path+File.separator+fileName;
        }
        return LocaPath;
    }

    //文件下载
    public static void download(HttpServletRequest request, HttpServletResponse response, String fileName, String paths) throws IOException {
        //下载文件本地地址
        String LocalPath = paths+"\\"+fileName;
        //获取输入流
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(LocalPath)));
        //转码,避免文件名中文乱码
        fileName = URLEncoder.encode(fileName);
        //设置文件下载头
        response.addHeader("Content-Disposition","attachment;filename="+fileName);
        //设置文件ContentType类型 然后会自己下载
        response.setContentType("multipart/form-data");
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        int len = 0;
        while((len = in.read()) != -1){
            out.write(len);
            out.flush();
        }
        out.close();
    }
}
